import '@/api/openai'
import { Method } from 'alova'
export const openAiService = () => {
    return {
        getModel: (url: string, apiKey: string) => {
            const method = Openais.general.get_models({ data: { url } })
            method.config.headers.Authorization = `Bearer ${apiKey}`
            return method.send()
        },
        ChatCompletion: ({ messages, model, tools }: any, callBack: (isDone: boolean, content?: string, tool_calls?: tool_call[]) => void): Method => {
            const method = Openais.general.post_chat_completions({
                data: {
                    model,
                    messages,
                    stream: true,
                    tools,
                }
            })
            method.send().then(async (response: Response) => {
                const reader = response.body?.getReader();
                const decoder = new TextDecoder();
                while (true) {
                    const { done, value } = await reader!.read()
                    if (done) {
                        callBack(true)
                        break
                    }
                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            const data = line.slice(6);
                            if (data === '[DONE]') continue;
                            try {
                                const json = JSON.parse(data);
                                const content = json.choices[0]?.delta?.content;
                                const tool_calls = json.choices[0]?.delta?.tool_calls;
                                if (content || tool_calls) {
                                    callBack(false, content, tool_calls)
                                }
                            } catch (e) {
                                console.error('Failed to parse chunk:', e);
                            }
                        }
                    }
                }
            })
            return method
        }
    }
}
